package com.pjc.utils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 字符串处理类
 * 
 * @author 王畅
 * @version 创建时间：2015-9-10 上午11:36:12
 */
public class CustomStringUtils {
	protected final static Logger log = LoggerFactory.getLogger(CustomStringUtils.class);

	/**
	 * HashMap根据key按照指定方式排序(ASC升序, DESC降序) ASC升序兼容c#字段排序
	 * 
	 * @author 王畅
	 * @param map
	 * @param sortMode
	 *            排序方式：ASC，DESC 任选其一
	 * @return
	 */
	public static List<Entry<String, String>> getSortMap(Map<String, String> map, final String sort) {
		if (map == null || map.isEmpty())
			return null;
		List<Entry<String, String>> mapList = new ArrayList<Entry<String, String>>(map.entrySet());
		Collections.sort(mapList, new Comparator<Map.Entry<String, String>>() {
			@Override
			public int compare(Entry<String, String> o1, Entry<String, String> o2) {
				boolean asc_order = (StringUtils.isBlank(sort)) || ("ASC".equalsIgnoreCase(sort));
				String i1 = (String) o1.getKey();
				String i2 = (String) o2.getKey();
				return (asc_order) ? i1.compareTo(i2) : i2.compareTo(i1);
			}

		});
		return mapList;
	}

	/**
	 * HashMap根据key按照指定方式排序且已c字符的方式组合(emp a=1&b=1)
	 * 
	 * @author 王畅
	 * @param map
	 * @param sort
	 *            排序方式：ASC，DESC 任选其一
	 * @return
	 */
	public static String getSortMapForString(Map<String, String> map, final String sort) {
		if (map == null || map.isEmpty())
			return null;
		StringBuilder sb = new StringBuilder("");
		List<Entry<String, String>> mapList = getSortMap(map, sort);
		for (Entry<String, String> entry : mapList) {
			if (!StringUtils.isBlank(entry.getKey()) && !StringUtils.isBlank(entry.getValue())) {
				sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
			}
		}
		return sb.toString().substring(0, sb.length() - 1);
	}

	/**
	 * 对List对象按照某个成员变量进行排序
	 * 
	 * @author 王畅
	 * @param <T>
	 *            List对象
	 * @param list
	 *            List对象
	 * @param sortField
	 *            排序的属性名称
	 * @param sortMode
	 *            排序方式：ASC，DESC 任选其一
	 */
	public static <T> void sortList(List<T> list, final String sortField, final String sortMode) {
		if (list == null || list.isEmpty())
			return;
		Collections.sort(list, new Comparator<T>() {
			@Override
			public int compare(T o1, T o2) {
				try {
					Class<?> clazz = o1.getClass();
					Field field = clazz.getDeclaredField(sortField); // 获取成员变量
					field.setAccessible(true); // 设置成可访问状态
					String typeName = field.getType().getName().toLowerCase(); // 转换成小写
					Object v1 = field.get(o1); // 获取field的值
					Object v2 = field.get(o2); // 获取field的值
					boolean ASC_order = (sortMode == null || "ASC".equalsIgnoreCase(sortMode));
					// 判断字段数据类型，并比较大小
					if (typeName.endsWith("string")) {
						String value1 = v1.toString();
						String value2 = v2.toString();
						return ASC_order ? value1.compareTo(value2) : value2.compareTo(value1);
					} else if (typeName.endsWith("short")) {
						Short value1 = Short.parseShort(v1.toString());
						Short value2 = Short.parseShort(v2.toString());
						return ASC_order ? value1.compareTo(value2) : value2.compareTo(value1);
					} else if (typeName.endsWith("byte")) {
						Byte value1 = Byte.parseByte(v1.toString());
						Byte value2 = Byte.parseByte(v2.toString());
						return ASC_order ? value1.compareTo(value2) : value2.compareTo(value1);
					} else if (typeName.endsWith("char")) {
						Integer value1 = (int) (v1.toString().charAt(0));
						Integer value2 = (int) (v2.toString().charAt(0));
						return ASC_order ? value1.compareTo(value2) : value2.compareTo(value1);
					} else if (typeName.endsWith("int") || typeName.endsWith("integer")) {
						Integer value1 = Integer.parseInt(v1.toString());
						Integer value2 = Integer.parseInt(v2.toString());
						return ASC_order ? value1.compareTo(value2) : value2.compareTo(value1);
					} else if (typeName.endsWith("long")) {
						Long value1 = Long.parseLong(v1.toString());
						Long value2 = Long.parseLong(v2.toString());
						return ASC_order ? value1.compareTo(value2) : value2.compareTo(value1);
					} else if (typeName.endsWith("float")) {
						Float value1 = Float.parseFloat(v1.toString());
						Float value2 = Float.parseFloat(v2.toString());
						return ASC_order ? value1.compareTo(value2) : value2.compareTo(value1);
					} else if (typeName.endsWith("double")) {
						Double value1 = Double.parseDouble(v1.toString());
						Double value2 = Double.parseDouble(v2.toString());
						return ASC_order ? value1.compareTo(value2) : value2.compareTo(value1);
					} else if (typeName.endsWith("boolean")) {
						Boolean value1 = Boolean.parseBoolean(v1.toString());
						Boolean value2 = Boolean.parseBoolean(v2.toString());
						return ASC_order ? value1.compareTo(value2) : value2.compareTo(value1);
					} else if (typeName.endsWith("date")) {
						Date value1 = (Date) (v1);
						Date value2 = (Date) (v2);
						return ASC_order ? value1.compareTo(value2) : value2.compareTo(value1);
					} else if (typeName.endsWith("timestamp")) {
						Timestamp value1 = (Timestamp) (v1);
						Timestamp value2 = (Timestamp) (v2);
						return ASC_order ? value1.compareTo(value2) : value2.compareTo(value1);
					} else {
						Method method = field.getType().getDeclaredMethod("compareTo", new Class[] { field.getType() });
						method.setAccessible(true);
						int result = (Integer) method.invoke(v1, new Object[] { v2 });
						return ASC_order ? result : result * (-1);
					}
				} catch (Exception ex) {
					log.error("将List<T>进行排序产生异常", ex);
				}
				return 0; // 未知类型，无法比较大小
			}
		});
	}

}
